package org.example.contestb.service.impl;





import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.example.contestb.Mapper.BPMapper;
import org.example.contestb.Mapper.PatientMapper;
import org.example.contestb.entity.BP;
import org.example.contestb.entity.DTO.ToExcelDTO;
import org.example.contestb.entity.Patient;
import org.example.contestb.entity.VO.DetailedPatientVO;
import org.example.contestb.entity.VO.RoughlyPatientVO;
import org.example.contestb.service.PatientService;
import org.example.contestb.util.TestFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import java.io.File;

@Service
public class PatientServiceImpl implements PatientService {

    @Autowired
    PatientMapper patientMapper;
    @Autowired
    BPMapper bpMapper;

    @Override
    public RoughlyPatientVO displayRoughly(Integer page, Integer pageSize) {
        Page<Patient> patientPage = new Page<>(page, pageSize);
        Page<Patient> resultPage = patientMapper.selectPage(patientPage, null);
        return RoughlyPatientVO.builder()
                .patient(resultPage.getRecords())
                .total(resultPage.getTotal())
                .build();
    }

    @Override
    public DetailedPatientVO displayDetailed(Integer patientId) {
        Patient patient = patientMapper.selectById(patientId);
        QueryWrapper<BP> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_id", patientId);
        List<BP> bpList = bpMapper.selectList(queryWrapper);

        return DetailedPatientVO.builder()
                .patient(patient)
                .bpList(bpList)
                .build();
    }

    @Override
    public List<Patient> patientSearch(String name) {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        List<Patient> patientList = patientMapper.selectList(queryWrapper);
        return patientList;
    }


    @Override
    public String patientToExcel(ToExcelDTO toExcelDTO) {
        // 参数校验
        if (toExcelDTO == null || CollectionUtils.isEmpty(toExcelDTO.getPatientId())) {
            throw new IllegalArgumentException("患者ID列表不能为空");
        }

        // 获取并处理基础路径
        String basePath = TestFileUtil.class.getResource("/").getPath();
        if (basePath.startsWith("/") && System.getProperty("os.name").toLowerCase().contains("win")) {
            basePath = basePath.substring(1);
        }

        // 构建文件对象
        String fileName = "patient_export_" + System.currentTimeMillis() + ".xlsx";
        File excelFile = new File(basePath, fileName);

        try {
            // 确保目录存在
            if (!excelFile.getParentFile().exists()) {
                excelFile.getParentFile().mkdirs();
            }

            // 查询和写入数据
            QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", toExcelDTO.getPatientId());
            List<Patient> patients = patientMapper.selectList(queryWrapper);

            if (CollectionUtils.isEmpty(patients)) {
                throw new RuntimeException("未找到对应的患者数据");
            }

            try (ExcelWriter excelWriter = EasyExcel.write(excelFile, Patient.class).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet("患者数据").build();
                excelWriter.write(patients, writeSheet);
            }

            return excelFile.getAbsolutePath();
        } catch (Exception e) {
            if (excelFile.exists()) {
                excelFile.delete();
            }
            throw new RuntimeException("导出Excel失败", e);
        }
    }
}